/**
 * Created by tianling on 2016/12/25.
 */
module.exports = class {
    constructor() {

        this.key = "iframe:partnersDict";
    }

    static init() {
        return new this();
    }

    /**
     * 获取系统模块列表
     * @param isReFlash
     * @param CB
     */
    async getDictItemsByDB() {
        return await global.DataBase.iframe_partners_dict.Access.findAll({
            where: {
                zd_IsShow: 1
            },
            order: ['zd_sort'],
            raw: true
        });
    };

    async Sync() {
        let ret = {};
        let partnersDict = await this.getDictItemsByDB();
        let partners = await global.DataBase.base.query("select distinct zd_partners_id from iframe_partners_dict left join iframe_orgstruct on OS_ID=zd_partners_id where OS_IsDel=0 and OS_Type=:OS_Type", {
            OS_Type: '001'
        });
        for (let partner of partners) {
            ret[partner.zd_partners_id] = await global.DataBase.iframe_partners_dict.Access.findAll({
                where: {
                    zd_partners_id: partner.zd_partners_id
                },
                raw: true
            })
        }
        ret['all'] = partnersDict;
        if (!global.Config.isShareMemory) {
            global.partners_dict = ret;

        } else {
            let redisClient = global.Redis.getClient();
            let pipeline = redisClient.pipeline();
            for (let key in ret) {
                if (key) {
                    pipeline.set(this.key + ":" + key, JSON.stringify(ret[key]));
                }

            }
            await pipeline.exec();

        }
        log.info("加载企业私有字典表成功");
        return true;


    };

    /**
     * 获取指定Label的字典表
     * @param Label
     * @constructor
     */
    async GetDictItems(partnersId, Label) {
        let DictItems = [];
        if (partnersId == undefined || partnersId == null || partnersId === 0 || partnersId === "0") {
            if (!global.Config.isShareMemory) {
                DictItems = global.partners_dict["all"];
            } else {
                let redisClient = global.Redis.getClient();
                DictItems = await redisClient.get(this.key + ":all");
            }

        } else {
            if (partnersId != '') {
                if (!global.Config.isShareMemory) {
                    DictItems = global.partners_dict[partnersId];
                } else {
                    let redisClient = global.Redis.getClient();
                    DictItems = await redisClient.get(this.key + ":" + partnersId);
                }
            }

        }
        if (Label) {
            return DictItems.filter(function (item) {
                if (item.zd_partners_id == partnersId && item.zd_label == Label && item.zd_IsShow == 1) {
                    return true;
                }
            });
        }

        return DictItems;
    };

    /**
     * 获取某个键值对
     * @param Label String
     * @param Name String
     * @returns {*}
     * @constructor
     */
    async GetDictItem(partnersId, Label, value) {
        let DictItems = await this.GetDictItems(partnersId, Label);
        let _items = DictItems.filter(function (item) {
            if (item.zd_partners_id == partnersId && item.zd_label == Label && item.zd_value == value) {
                return true;
            }
        });
        if (_items.length > 0) {
            return _items[0];
        }
        return null;
    };

    async GetDictItemByID(partnersId, ID) {
        let DictItems = await this.GetDictItems(partnersId);
        let _items = DictItems.filter(function (item) {
            if (item.zd_ID === Number(ID)) {
                return true;
            }
        });
        if (_items.length > 0) {
            return _items[0];
        }
        return null;
    };

    /**
     * 获取相同分类下的一组值的名称
     * @param {String} Label  字典表分类
     * @param {Array} Values 值数组
     */
    async GetDictNames(partnersId, Label, Values) {
        let Names = [];
        Values.map(async (item) => {
            if (item && item != "") {
                let dict = await this.GetDictItem(partnersId, Label, item);
                if (dict) {
                    Names.push(dict.zd_Name);
                }
            }
        });
        return Names;
    };

    async getChildrenValues(partnersId, Label, value) {
        let cur = await this.GetDictItem(partnersId, Label, value);
        let Items = await this.GetDictItems(partnersId, Label);
        let Childrens = [];
        for (let i = 0; i < Items.length; i++) {
            let item = Items[i];
            if (item.zd_ParentID == cur.zd_ID) {
                Childrens.push("" + item.zd_value + "");
                if (item.zd_IsParent == 1) {
                    Childrens = Childrens.concat(await this.getChildrenValues(partnersId, Label, item.zd_value));
                }
            }
        }
        return Childrens;
    };

    async getChildrensModel(partnersId, Label, value) {
        let cur = await this.GetDictItem(partnersId, Label, value);
        let Items = await this.GetDictItems(partnersId, Label);
        let Childrens = [];
        for (let i = 0; i < Items.length; i++) {
            let item = Items[i];
            if (item.zd_ParentID == cur.zd_ID) {
                Childrens.push(item);
                if (item.zd_IsParent == 1) {
                    Childrens = Childrens.concat(await this.getChildrensModel(partnersId, Label, item.zd_value));
                }
            }
        }
        return Childrens;
    };

    /**
     * 获取所有父级的值数组
     * @param {*} Label 
     * @param {*} value 
     */
    async GetParentsValue(partnersId, Label, value) {
        let ParentsModels = await this.GetParentsModel(partnersId, Label, value);
        let Values = [];
        for (let i = ParentsModels.length - 1; i > -1; i--) {
            Values.push(ParentsModels[i].zd_value);
        }
        return Values;
    };

    /**
     * 获取所有父级的名称数组
     * @param {*} Label 
     * @param {*} value 
     */
    async GetParentsName(partnersId, Label, value) {
        let ParentsModels = await this.GetParentsModel(partnersId, Label, value);
        let Names = [];
        for (let i = ParentsModels.length - 1; i > -1; i--) {
            Names.push(ParentsModels[i].zd_Name);
        }
        return Names;
    };

    /**获取所有的父级模型**/
    async GetParentsModel(partnersId, Label, value) {
        let item = await this.GetDictItem(partnersId, Label, value);
        if (item) {
            return await this.GetParentsModelByID(partnersId, item.zd_ID);
        }
        return [];
    };

    async GetParentsModelByID(partnersId, ChildrenID) {
        let Parents = [];
        let item = await this.GetDictItemByID(partnersId, ChildrenID);
        if (item) {
            Parents.push(item);
            Parents = await Parents.concat(this.GetParentsModelByID(partnersId, item.zd_ParentID));
        }
        return Parents;
    };

    async GetParentsValueByID(partnersId, ChildrenID) {
        let Parents = [];
        let item = await this.GetDictItemByID(partnersId, ChildrenID);
        if (item) {
            Parents.push(item.zd_value);
            Parents = Parents.concat(await this.GetParentsValueByID(item.zd_ParentID));
        }
        return Parents;
    };

    async GetTreeData(partnersId, Label, ParentID) {
        let Items = await this.GetDictItems(partnersId, Label);
        //console.log('items:',Items);
        let data = [];
        let getChildrens = function (pid) {
            let cdata = [];
            for (let i = 0; i < Items.length; i++) {
                let item = Items[i];
                if (item.zd_ParentID === pid) {
                    let data_item = {
                        title: item.zd_Name,
                        value: item.zd_value,
                        key: item.zd_ID,
                        children: getChildrens(item.zd_ID)
                    };
                    if (data_item.children.length === 0) delete data_item.children;
                    cdata.push(data_item);
                }
            }
            return cdata;
        };
        if (ParentID > 0) {
            let curP = await this.GetDictItemByID(partnersId, ParentID);
            data.push({
                title: curP.zd_Name,
                value: curP.zd_value,
                key: curP.zd_ID,
                children: getChildrens(curP.zd_ID)
            });
        } else {
            data = getChildrens(0);
        }
        return data;

    };


};